package com.mvp.dagger.translate;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mvp.dagger.translate.base.BaseActivity;
import com.mvp.dagger.translate.bean.TranslateResult;
import com.mvp.dagger.translate.mvp.contract.MainContract;
import com.mvp.dagger.translate.mvp.presenter.MainPresenter;
import com.mvp.dagger.translate.tool.MD5;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements MainContract.View {
    public static final String APPID = "20180723000188092";
    public static final String SECRET_KEY = "OppaY8bOLsI118_LHYxN";
    @Inject
    String className;
    @Inject
    SharedPreferences sp;
    @Inject
    MainPresenter presenter;
    @BindView(R.id.edit_text)
    EditText editText;
    @BindView(R.id.translate_btn)
    TextView translateBtn;
    @BindView(R.id.translate_text)
    TextView translateText;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void getTranslateSuccess(TranslateResult model) {

        try {
            String dst = "";
            for (int i = 0; i < model.getTrans_result().size(); i++) {
                if (i == 0) {
                    dst = model.getTrans_result().get(i).getDst();
                } else {
                    dst = dst + "\n" + model.getTrans_result().get(i).getDst();
                }
            }
            translateText.setText(dst);
        }catch (Exception e){
            e.getStackTrace();
        }

    }

    @OnClick({R.id.translate_btn})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.translate_btn:
                getTranslate();
                break;
        }
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APPID);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = APPID + query + salt + SECRET_KEY; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

    private void getTranslate() {
        Map<String, String> map = buildParams(editText.getText().toString().trim(), "zh_ch", "en");
        presenter.getTranslate(map);
    }


    @Override
    public void getTranslateFail(String msg) {
        Toast.makeText(this, msg.toString(), Toast.LENGTH_SHORT).show();
    }
}
